package com.bbcare.mqservice.utils.rockermq;


import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;


import java.util.Properties;

@Component
public class ProducerFactory {
    private static  final Logger logger = LogManager.getLogger();


    @Value("${aliyun.mq.access_id}")
    private String ACCESS_ID;
    @Value("${aliyun.mq.access_key}")
    private String SecretKey;
    @Value("${aliyun.mq.access_expired_time}")
    private String ACCESS_EXPIRED_TIME;
    @Value("${aliyun.mq.namesrv_addr}")
    private String NAMESRV_ADDR;
    @Value("${aliyun.mq.group_id}")
    private String GROUP_ID;

    public static final String tag = "*";

    //消费者实例配置列表

    private static Producer producer;
    public ProducerFactory(){

    }

    /**
     * 消费者启动
     * @throws Exception
     */
    public void start() {

        // producer 实例配置初始化
        Properties properties = new Properties();
        //您在控制台创建的Producer ID
        properties.setProperty(PropertyKeyConst.GROUP_ID, GROUP_ID);
        // AccessKey 阿里云身份验证，在阿里云服务器管理控制台创建
        properties.setProperty(PropertyKeyConst.AccessKey, ACCESS_ID);
        // SecretKey 阿里云身份验证，在阿里云服务器管理控制台创建
        properties.setProperty(PropertyKeyConst.SecretKey, SecretKey);
        //设置mqtt发送质量，
        properties.setProperty(PropertyKeyConst.MqttQOS,"2");
        //设置发送超时时间，单位毫秒
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, ACCESS_EXPIRED_TIME);
        // 设置 TCP 接入域名(此处以公共云生产环境为例)，设置 TCP 接入域名，进入 MQ 控制台的消费者管理页面，在左侧操作栏单击获取接入点获取
        properties.setProperty(PropertyKeyConst.NAMESRV_ADDR, NAMESRV_ADDR);
        producer = ONSFactory.createProducer(properties);
        // 在发送消息前，初始化调用start方法来启动Producer，只需调用一次即可，当项目关闭时，自动shutdown
        producer.start();

    }

    public  Producer getProducer()
    {
        if (producer == null)
        {
            synchronized(Producer.class) {
                if (producer == null)
                    start();
            }
        }
        return producer;
    }




    public void shutdown(){
        if(producer!=null)
            producer.shutdown();
    }

}
